package com.wy.business.market.market.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ExceptionMapping;
import org.apache.struts2.convention.annotation.ExceptionMappings;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.wy.business.market.market.pojos.TMarketFunctionRemarkInfo;
import com.wy.business.market.market.services.MarketAppsManageService;
import com.wy.framework.actions.AbstractBaseAction;
import com.wy.framework.dao.ErrorSqlException;
import com.wy.framework.exceptions.ServiceException;
import com.wy.framework.pojos.TSysUserinfo;

/**
 * 
 * 项目名称：vanyplatform
 * 类名称：AppsAction
 * 类描述：APP发现功能接口
 * 创建人：高振泰
 * 创建时间：2016-3-15 下午3:54:46
 * 修改人：
 * 修改时间：2016-3-15 下午3:54:46
 * 版本信息：@version 1.0
 * Copyright (c) 2016万雍科技（上海）有限公司-版权所有  
 * 修改备注：
 * @version
 */
@ParentPackage("json")
@Namespace("/market/apps")
@ExceptionMappings({ @ExceptionMapping(exception = "java.lange.RuntimeException", result = "error") })
public class AppsAction extends AbstractBaseAction {
	private static final long serialVersionUID = 1L;
	private static Log logger = LogFactory.getLog(AppsAction.class);

	@Autowired
	private MarketAppsManageService appsManageService;
	
	private List<Map> rows;
	
	/**
	 * 
	 * Function Name               list                                   
	 * @return          		             
	 * @throws Exception 
	 * @description TODO(APP发现列表)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-15 下午3:44:26           高振泰                     Initial
	 **********************************************************************
	 */
	@SuppressWarnings({ "unchecked", "unused", "rawtypes" })
	@Action(value = "list", results = { @Result(name = "success", location = "/jsps/apiEncrypt.jsp") })
	public String list() throws Exception{
//		TSysUserinfo loginUser = loginUser();
		rows=new ArrayList();
		List<Map> mapLists=new ArrayList<Map>();
		try {
			List<Map> functionList = appsManageService.getAppList(null);
			List<Map> appTypeList = appsManageService.getAppType();
			List<Map> appTypeListTemp = new ArrayList();
			for(int i=0;i<appTypeList.size();i++){
				if(appTypeList.get(i).get("CATEGORYNAME").equals("热门") && i!=0){
					appTypeListTemp.add(0,appTypeList.get(i));
				}else{
					appTypeListTemp.add(appTypeList.get(i));
				}
			}
			for(int i=0;i<appTypeListTemp.size();i++){
				Map map = new HashMap(); 
				List applist=new ArrayList();
				String appTypeDesc=(String) appTypeListTemp.get(i).get("CATEGORYNAME");
				String appTypeId=(String) appTypeListTemp.get(i).get("CATEGORYID");
				map.put("typeDesc", appTypeDesc);
				for(int j=0;j<functionList.size();j++){
					String functionTypeId=(String) functionList.get(j).get("CATEGORYID");
					if(appTypeId.equals(functionTypeId)){
						functionList.get(j).remove("CATEGORYNAME");
						applist.add(functionList.get(j));
					}
				}
				map.put("type2Apps",applist);
				if(applist.size()!=0)
					rows.add(map);
			}
			
		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	/**
	 * 
	 * Function Name               list                                   
	 * @return          		             
	 * @throws Exception 
	 * @description (APP发现列表)根据userId
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-15 下午3:44:26           张旭星                     Initial
	 **********************************************************************
	 */
	@SuppressWarnings({ "unchecked", "unused", "rawtypes" })
	@Action(value = "listByUserId", 
	results = { @Result(name = "success", type = "json", params = {
			"noCache", "true", "contentType", "text/html", "ignoreHierarchy",
	"false"}) })
	public String listByUserId() throws Exception{
		String userId = ServletActionContext.getRequest().getParameter("userId");
		TSysUserinfo loginUser = loginUser();
		rows=new ArrayList();
		List<Map> mapLists=new ArrayList<Map>();
		try {
			List<Map> functionList = appsManageService.getAppList(userId);
			List<Map> appTypeList = appsManageService.getAppType();
			List<Map> appTypeListTemp = new ArrayList();
			for(int i=0;i<appTypeList.size();i++){
				if(appTypeList.get(i).get("CATEGORYNAME").equals("热门") && i!=0){
					appTypeListTemp.add(0,appTypeList.get(i));
				}else{
					appTypeListTemp.add(appTypeList.get(i));
				}
			}
			for(int i=0;i<appTypeListTemp.size();i++){
				Map map = new HashMap(); 
				List applist=new ArrayList();
				String appTypeDesc=(String) appTypeListTemp.get(i).get("CATEGORYNAME");
				String appTypeId=(String) appTypeListTemp.get(i).get("CATEGORYID");
				map.put("typeDesc", appTypeDesc);
				for(int j=0;j<functionList.size();j++){
					String functionTypeId=(String) functionList.get(j).get("CATEGORYID");
					if(appTypeId.equals(functionTypeId)){
						functionList.get(j).remove("CATEGORYNAME");
						applist.add(functionList.get(j));
					}
				}
				map.put("type2Apps",applist);
				if(applist.size()!=0)
					rows.add(map);
			}
			
		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * Function Name               updateViews                                   
	 * @return
	 * @throws ServiceException          		             
	 * @description 增加访问量
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-1-4 下午1:46:43           张旭星                     Initial
	 **********************************************************************
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Action(value = "updateViews", results = { @Result(name = "success", location = "/jsps/apiEncrypt.jsp") })
	public String updateViews() throws ServiceException {
		try {
			String functionId = ServletActionContext.getRequest().getParameter("functionId");
			rspCode = appsManageService.updateViews(functionId);
		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	/**
	 * 
	 * Function Name               show                                   
	 * @return          		             
	 * @description TODO(查看应用详情)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-16 下午2:33:25           高振泰                     Initial
	 **********************************************************************
	 */
	@SuppressWarnings({ "unchecked", "unused", "rawtypes" })
	@Action(value = "show", results = { @Result(name = "success", location = "/jsps/apiEncrypt.jsp") })
	public String show(){
		rows=new ArrayList();
		String functionId=ServletActionContext.getRequest().getParameter("functionId");
		try {
			List<Map> appDetail=appsManageService.getAppDetailForFunctionId(functionId);
			List<Map> appScreen=new ArrayList();
			for(int i=0;i<appDetail.size();i++){
				Map screenMap=new HashMap();
				screenMap.put("PICURL", appDetail.get(i).get("picurl"));
				appScreen.add(screenMap);
			}
			Map map = new HashMap(); 
		    map.put("FUNCTIONNAME", appDetail.get(0).get("functionname"));
		    map.put("ICONNAME", appDetail.get(0).get("iconname"));
		    map.put("ACTIONURL", appDetail.get(0).get("actionurl"));
		    map.put("APPSIZE", appDetail.get(0).get("appsize"));
		    map.put("APPZIPURL", appDetail.get(0).get("appzipurl"));
		    map.put("APPTYPE", appDetail.get(0).get("apptype"));
		    map.put("VERSIONNO", appDetail.get(0).get("versionno"));
		    map.put("APPDOWNCTN", appDetail.get(0).get("appdownctn"));
		    map.put("PROVIDER", appDetail.get(0).get("provider"));
		    map.put("SUBMITTIME", appDetail.get(0).get("submittime"));
		    map.put("DESCRIPTION", appDetail.get(0).get("description"));
			map.put("SCORE", appDetail.get(0).get("score"));
			map.put("APPSCREEN", appScreen);
			rows.add(map);
		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	@SuppressWarnings({ "unchecked", "unused", "rawtypes" })
	@Action(value = "remark", results = { @Result(name = "success", location = "/jsps/apiEncrypt.jsp") })
    public String remark(){
		String functionId=ServletActionContext.getRequest().getParameter("functionId");
		int  pageNo=Integer.parseInt(ServletActionContext.getRequest().getParameter("pageNo"));
		int  pageSize=Integer.parseInt(ServletActionContext.getRequest().getParameter("pageSize"));
		try {
			rows=new ArrayList();
			Map rowsMap=new HashMap();
			List<Map> remarkList=appsManageService.getAppRemarkList(functionId, pageNo, pageSize);
			rowsMap.put("avgScore", "0");
			rowsMap.put("remarkCount", "0");
			for(int i=0;i<remarkList.size();i++){
				remarkList.get(i).remove("AVGSCORE");
				remarkList.get(i).remove("REMARKCOUNT");
				rowsMap.put("avgScore", remarkList.get(0).get("AVGSCORE"));
				rowsMap.put("remarkCount", remarkList.get(0).get("REMARKCOUNT"));
			}
			rowsMap.put("remarkList", remarkList);
			rows.add(rowsMap);
		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}
    	return SUCCESS;
    }
	
	@SuppressWarnings({ "unchecked", "unused", "rawtypes" })
	@Action(value = "write", results = { @Result(name = "success", location = "/jsps/apiEncrypt.jsp") })
	public String write(){
		String functionId=ServletActionContext.getRequest().getParameter("functionId");
		int score=Integer.parseInt(ServletActionContext.getRequest().getParameter("score"));
		String content=ServletActionContext.getRequest().getParameter("content");
		String userId=ServletActionContext.getRequest().getParameter("userId");
		TMarketFunctionRemarkInfo tMarketFunctionRemarkInfo=new TMarketFunctionRemarkInfo();
		tMarketFunctionRemarkInfo.setFunctionId(functionId);
		tMarketFunctionRemarkInfo.setScore(score);
		tMarketFunctionRemarkInfo.setContent(content);
		tMarketFunctionRemarkInfo.setUserId(userId);
		tMarketFunctionRemarkInfo.setOperatorAccount(userId);
		try {
			appsManageService.saveRemark(tMarketFunctionRemarkInfo);
		} catch (ErrorSqlException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public List getRows() {
		return rows;
	}

	public void setRows(List rows) {
		this.rows = rows;
	}

}
